//
//  UIImage+Compress.m
//  NoNeedle
//
//  Created by Ming Tian on 2017/3/7.
//  Copyright © 2017年 Ming Tian. All rights reserved.
//

#import "UIImage+Compress.h"

@implementation UIImage (Compress)

/**
 *  将image压缩到指定大小
 *  param image:待压缩图片
 *  param size:输出文件大小(最大值)
 */
+ (NSData *)compressImage:(UIImage *)image ToSize:(CGFloat)size {
    NSData * data = UIImageJPEGRepresentation(image, 1.0);
    CGFloat dataKBytes = data.length/1000.0;
    CGFloat maxQuality = 0.95f;
    CGFloat lastData = dataKBytes;
    while (dataKBytes > size && maxQuality > 0.01f) {
        maxQuality = maxQuality - 0.01f;
        data = UIImageJPEGRepresentation(image, maxQuality);
        dataKBytes = data.length / 1000.0;
        if (lastData == dataKBytes) {
            break;
        }else{
            lastData = dataKBytes;
        }
    }
    return data;
}

/**
 *  param size:输出文件大小(最大值),单位:kb
 */
- (NSData *)compressToSize:(CGFloat)size {
    NSData * data = UIImageJPEGRepresentation(self, 1.0);
    CGFloat dataKBytes = data.length/1000.0;
    CGFloat maxQuality = 0.95f;
    CGFloat lastData = dataKBytes;
    while (dataKBytes > size && maxQuality > 0.01f) {
        maxQuality = maxQuality - 0.01f;
        data = UIImageJPEGRepresentation(self, maxQuality);
        dataKBytes = data.length / 1000.0;
        if (lastData == dataKBytes) {
            break;
        }else{
            lastData = dataKBytes;
        }
    }
    return data;
}

@end
